<?php
/**
 * Created by PhpStorm.
 * User: 张辉
 * Date: 2018/7/23
 * Time: 15:27
 */
namespace app\common\service;

use app\common\library\CommonFun;
use app\common\model\user\UserBaseModel;
use app\common\model\user\UserCoinModel;
use app\common\model\user\UserPairModel;
use app\common\model\user\UserWxModel;

/**
 * 获取微信用户信息
 */
class WXService
{

    public static $AppID = "";
    public static $AppSecret = "";
    public static $url = '';

    public function __construct( $app_type = 'wxH5' )
    {
        self::init( $app_type );
    }

    public static function init( $app_type = 'wxH5' )
    {
        // 初始化微信配置
        CommonFun::get_other_config( 'wx_config', 2 );
        $wx_config = config( $app_type );
        self::$AppID = $wx_config['AppID'];
        self::$AppSecret = $wx_config['AppSecret'];
        self::$url = $wx_config['url'];
    }

    /**
     * 通过授权后code获取秘钥
     * @param $code
     * @return bool|mixed
     */
    public static function getAccessTokenByCode( $code )
    {
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".self::$AppID."&secret=".self::$AppSecret."&code=".$code."&grant_type=authorization_code";
        $res = file_get_contents( $url );
        $accessInfo = json_decode( $res, true );
        if ( isset( $accessInfo['errcode'] ) && $accessInfo['errcode'] ){
            return false;
        }
        return $accessInfo;
    }

    /**
     * 通过授权refresh_token获取refresh_token
     * @param $refresh_token
     * @return bool|mixed|string
     */
    public static function getRefreshToken( $refresh_token )
    {
        $url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=".self::$AppID."&grant_type=refresh_token&refresh_token=".$refresh_token;
        $res = file_get_contents( $url );
        $res = json_decode( $res, true );
        if ( isset( $res['errcode'] ) && $res['errcode'] ){
            return false;
        }

        return $res;
    }

    /**
     * 获取用户基本信息
     * @param $openid
     * @param $access_token
     * @return mixed
     */
    public static function getUserInfo( $openid, $access_token )
    {
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid;
        $res = file_get_contents( $url );
        return json_decode( $res, true );
    }

    /**
     * 通过token获取微信用户基本信息
     * @param $code
     * @return bool|mixed
     */
    public static function getUserInfoByCode( $code )
    {
        $accessInfo = self::getAccessTokenByCode( $code );
        if ( !$accessInfo ){
            return false;
        }

        $info = self::getUserInfo( $accessInfo['openid'], $accessInfo['access_token'] );
        return $info;
    }

    /**
     * 微信登录
     * @param array $param 微信信息
     * @param string $registerType 请求信息
     * @return mixed
     */
    public static function login( array $param, $registerType )
    {
        $open_id = $param['openid'];
        $union_id = $param['unionid'];
        $avatar = $param['headimgurl'];
        $city = $param['city'];
        $country = $param['country'];
        $nickname = $param['nickname'];
        $province = $param['province'];
        $sex = $param['sex'];

        // 模型
        $modelUserBase = UserBaseModel::getInstance();
        $modelUserWx = UserWxModel::getInstance();

        // 判断用户是否存在
        $userWxData = $modelUserWx->get_data_by_unique_key('union_id', $union_id, false);
        // 微信用户不存在
        if ( !$userWxData ) {
            $is_new_user = 1;
            $insert_base = array(
                'open_id' => $open_id,
                'union_id' => $union_id,
                'app_login_type' => 2,
                'register_type' => $registerType,
            );

            $base_res = $modelUserBase->add_data($insert_base);

            // 插入失败
            if( !$base_res ){
                return false;
            }

            $wx_res = array();

            if ( $base_res ) {
                $insert_wx = array(
                    'user_id' => $base_res,
                    'open_id' => $open_id,
                    'union_id' => $union_id,
                    'avatar' => $avatar,
                    'nickname' => $nickname,
                    'sex' => $sex,
                    'country' => $country,
                    'province' => $province,
                    'city' => $city,
                );
                $wx_res = $modelUserWx->add_data($insert_wx);
                if ( !$wx_res ) {
                    $modelUserBase->delete_data_by_id($base_res);
                    return false;
                }
                // 赋值返回
                $wx_res = $insert_wx;
            }
        }else {
            // 用户存在, 更新用户微信信息
            $is_new_user = 0;
            $update_wx = array(
                'avatar' => $avatar,
                'nickname' => $nickname,
                'sex' => $sex,
                'country' => $country,
                'province' => $province,
                'city' => $city,
            );
            $wx_res = $modelUserWx->update_data($userWxData['id'], $update_wx);
            // 更新用户信息
            $update_base = array(
                'app_login_type' => 2,
            );
            $modelUserBase->update_data($userWxData['user_id'], $update_base);
        }

        $res = [
            'user_id' => $wx_res['user_id'],
            'is_new_user' => $is_new_user
        ];

        return $res;

    }


    /**
     * 绑定微信
     * @param $user_id
     * @param array $param
     * @return array
     * @throws \Exception
     */
    public static function BindWx( $user_id, array $param = array() )
    {
        $open_id = $param['openid'];
        $union_id = $param['unionid'];
        $avatar = $param['headimgurl'];
        $city = $param['city'];
        $country = $param['country'];
        $nickname = $param['nickname'];
        $province = $param['province'];
        $sex = $param['sex'];
        // 模型 更新数据(Base, WX, UserCoin, UserPair)
        $modelUserBase = UserBaseModel::getInstance();
        $modelUserWx = UserWxModel::getInstance();
        $modelUserCoin = UserCoinModel::getInstance();
        $modelUserPair = UserPairModel::getInstance();
        // 用户数据
        $user_data = $modelUserBase->get_data_by_id($user_id, false);
        $current_union_id = $user_data['union_id'];
        // 提交的微信的数据
        $BindWxData = $modelUserWx->get_data_by_unique_key('union_id', $union_id, false);
        if ( $BindWxData ) {
            $_BindWxUserID = $BindWxData['user_id'];
            $_BindWxUserData = $modelUserBase->get_whole_user_data($_BindWxUserID);
            if ( $_BindWxUserData['is_bind_mobile'] ) {
                throw new \Exception('这个微信已经绑定了手机号，请使用别的微信！'  );
            }
            // 先删除, 防止绑定微信冲突
            $modelUserWx->delete_data_by_id($BindWxData['id']);
        }

        // 1) 先更新UserBase
        $update_user_base = array(
            "union_id" => $union_id,
            "open_id" => $open_id,
        );
        $updateUserBaseRes = $modelUserBase->update_data($user_id, $update_user_base);

        if ( !$updateUserBaseRes ) {
            throw new \Exception( '数据保存失败',9007  );
        }
        // 2) 更新(新增)用户微信
        $update_user_wx = array(
            'open_id' => $open_id,
            'union_id' => $union_id,
            'avatar' => $avatar,
            'nickname' => $nickname,
            'sex' => $sex,
            'country' => $country,
            'province' => $province,
            'city' => $city,
        );
        if ( $current_union_id ) {
            // 之前绑定微信
           $modelUserWx->update_data_by_where(array("user_id"=>$user_id), $update_user_wx);
        }else {
            // 之前没有绑定
            $update_user_wx["user_id"] = $user_id;
            $modelUserWx->add_data($update_user_wx);
        }
        // 3) 判断用户是否存在->提交过来的微信UnionID数据
        if ( $BindWxData ) {
            // 存在微信登录 删除用户/微信/持仓/自选
            $last_uid = $BindWxData["user_id"];
            $modelUserBase->delete_data_by_id($last_uid);
            // 删除持仓/自选
            $deleteUserCoinPairMap = array(
                "user_id" => $last_uid
            );
            $modelUserCoin->where($deleteUserCoinPairMap)->delete();
            $modelUserPair->where($deleteUserCoinPairMap)->delete();
        }

        return $modelUserBase->get_whole_user_data( $user_id ) ?: [];
    }








}